var setting = {
    view:{
        selectedMulti: false
    },
    data: {
        simpleData: {
            enable: true,
            pIdKey: "pid"
        }
    },
    check:{
        enable:false,
        chkStyle: "checkbox",
		autoCheckTrigger: true
    },
    callback: {
        beforeCheck: beforeCheck,
        onClick : zTreeOnClick
    }

};

function beforeCheck(treeId, treeNode){
    var zTree = $.fn.zTree.getZTreeObj("treePer"),
        nodes = zTree.getCheckedNodes();
    return true;
}
function zTreeOnClick(event, treeId, treeNode,clickFlag){
	
    var zTree = $.fn.zTree.getZTreeObj("treePer");
    var nodeObj = zTree.getNodeByTId(treeId);
    zTree.checkNode(treeNode,treeNode.checked==true?false:true,false,true);
    var treeids = treeNode.guid;
    permissionTable(treeids);
    $(".treeidpara").val(treeids);
    
}

function push_message(){
    var empIds=treedepId.split("dept")[1];
    if (empIds == undefined || $.trim(empIds) == "") {
        alert("请选择所属部门！");
        return false;
    }
}


$(function(){
	var editArr = [];
//	权限菜单
	ajaxSer.permissionTree(function(data){
		var obj=eval("("+data+")");
		var zNodes = obj.nodes;
        $.fn.zTree.init($("#treePer"), setting, zNodes);
        var treeObj = $.fn.zTree.getZTreeObj("treePer");
      	treeObj.expandAll(true);
	});
//    新增
    $(".permissopen").on('click',function(){
    	if($(".treeidpara").val() != "" && $(".treeidpara").val() != null){
	    	layer.open({
	    	  title: '新增', 
			  skin: 'demo-class',
			  btn: ['确认', '取消'],
			  content: $(".permissform").html(),
			  success: function(layero, index){
				    console.log(layero, index);
				    $(layero).find('#addpermiss').validate();
			  },
			  yes:function(index, layero){
				  if($(layero).find('#addpermiss').valid()){
					  var treeid = $(layero).find('.treeidpara').val();
					  var treeJson = $(layero).find('form').serializeObject();
					  ajaxSer.permissionAdd(treeJson,function(data){
						  if(data.type == "2"){
							  permissionTable(treeid).draw();
						  }
						  layer.msg(data.msg);
					  });
					  //这里是回调，点击确认的时候执行的方法，最后一个关闭需要手动调用
					  layer.close(index);
				  }
			  },
			  cancel:function(index){
				  layer.close(index);
			  }
			});
    	}else{
    		layer.msg('请选择左侧菜单新增');
    	}
    });
    
//    修改
    $(".permissedit").on('click',function(){
    	var choose_a = $('#datatables tbody :checkbox:checked');
        var c_tIds;
        c_tIds = choose_a.eq(0).val();
        if (c_tIds == undefined || $.trim(c_tIds) == "") {
        	layer.msg("请选择一条记录！");
            return false;
        }
        if(choose_a.length != 1){
        	layer.msg("只能选择一条记录！");
            return false;
        }
    	layer.open({
    	  title: '修改', 
  		  skin: 'demo-class',
  		  btn: ['确认', '取消'],
  		  content: $(".permissform").html(),
  		  success: function(layero, index){
  			  	//修改之前执行填充操作
  			  $(layero).find('#addpermiss').validate();
  			  ajaxSer.permissionEditPull(c_tIds,function(data){
  					var nameVal = $(layero).find('form input');
					for(var i=0; i<nameVal.length;i++){
						if(data[$(nameVal[i]).attr('name')]){
							$(nameVal[i]).val(data[$(nameVal[i]).attr('name')])
						} 
  				  }
  			  })
  		  },
  		  yes:function(index, layero){
  			if($(layero).find('#addpermiss').valid()){
  			  var treeid = $(layero).find('.treeidpara').val();
  			  var treeJson = $.extend({},{'Id':c_tIds},$(layero).find('form').serializeObject());
  			  ajaxSer.permissionEdit(treeJson,function(data){
  				 if(data.type == "2"){
					  permissionTable(treeid).draw();
				  }
				  layer.msg(data.msg);
  			  });
  			  layer.close(index);
  			}
  		  },
  		  cancel:function(index){
  			  layer.close(index);
  		  }
  		});
    });
    
    
//    删除
    $(".permissdel").on('click',function(){
    	var del_tIds = "";
        var data_a = $("#datatables tbody :checkbox:checked");
        $.each(data_a, function (n) {
            if (n == 0) {
                del_tIds = data_a.eq(n).val();
            } else {
                del_tIds = del_tIds + "," + data_a.eq(n).val();
            }
        })
        if (del_tIds == undefined || $.trim(del_tIds) == "") {
        	layer.msg("请选择一条记录！");
            return false;
        }
    	layer.confirm('确认删除?', {icon: 3, title:'删除'}, function(index){
    		ajaxSer.permissionDel(del_tIds,function(data){
    			if (data.type == "2") {
                	permissionTable($(".treeidpara").val()).draw();
                }
    			layer.msg(data.msg);
    		});
		    layer.close(index);
		});
    });
    
  //单击行选中事件
    $('#datatables tbody').on('click', 'tr', function () {
        var table = $('#datatables').DataTable();
        var data = table.row(this).data();
        if ($(this).hasClass('selected')) {
            $(this).removeClass('selected');
            $('#check' + data.id).prop("checked", false);
        } else {
            $(this).addClass('selected');
            $('#check' + data.id).prop("checked", true);
        }
    });
    //全选
    $(".checkall").click(function () {
        var check = $(this).prop("checked");
        $(".checkchild").prop("checked", check);
        var cells = new Array();
        $('#datatables tbody tr').each(function () {
            if (check) {
                $(this).addClass('selected');
            } else {
                $(this).removeClass('selected');
            }
        });
    });
});


function permissionTable(treeids) {
	if($.fn.dataTable.isDataTable('#datatables')){
        _table = $('#datatables').DataTable();
        _table.destroy();
	}
    //初始化表格
    var table = $("#datatables").DataTable(
            {
                "bServerSide": true,
                "ordering": false,
                "searching": false,
                "bLengthChange": false,
                "pagingType": "full_numbers",
                language: {
                    "sProcessing": "处理中...",
                    "sLengthMenu": "显示 _MENU_ 项结果",
                    "sZeroRecords": "没有匹配结果",
                    "bPaginate": true,
                    "bFilter": true,
                    "sInfo": "显示第  _START_ 至  _END_ 项结果，共  _TOTAL_ 项，当前位置  第_PAGE_页",
                    "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                    "sInfoFiltered": "(由  _MAX_ 项结果过滤)",
                    "sInfoPostFix": "",
                    "sSearch": "搜索:",
                    "sUrl": "",
                    "sEmptyTable": "表中数据为空",
                    "sLoadingRecords": "载入中...",
                    "sInfoThousands": ",",
                    "oPaginate": {
                        "sFirst": "首页",
                        "sPrevious": "上页",
                        "sNext": "下页",
                        "sLast": "末页"
                    }
                },
                "bDeferRender": false,
                "retrieve": true,
                "processing": true,
                "ajax": {
                    url: webroot + "/Permssion/listData.do",
                    type: "POST",
                    data: function (obj) {
                        obj.sysMenuId = treeids;
                    }
                },
                "columns": [{
                    "sClass": "text-center",
                    "data": "id",
                    "render": function (data, type, full, meta) {
                        return '<input type="checkbox"  class="checkchild"  value="' + data + '" id="check' + data + '"/>';
                    },
                    "bSortable": false
                },{
                	"sClass": "text-left",
                    "data": "permissionIndex"
                },{
                	"sClass": "text-left",
                    "data": "permissionName"
                }]
            });

    return table;
}